import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

export const useAppStore = defineStore('app', () => {
    const sidebarCollapsed = ref(false);
    const mobileSidebarOpen = ref(false);
    const darkMode = ref(false); // 添加暗黑模式状态
    
    // 自动检测移动端
    const isMobile = ref(window.innerWidth <= 768);

    // 响应窗口大小变化
    if (typeof window !== 'undefined') {
        window.addEventListener('resize', () => {
            isMobile.value = window.innerWidth <= 768;
        });
    }

    // 切换侧边栏状态
    const toggleSidebar = () => {
        if (isMobile.value) {
            mobileSidebarOpen.value = !mobileSidebarOpen.value;
        } else {
            sidebarCollapsed.value = !sidebarCollapsed.value;
        }
    };

    // 关闭移动端侧边栏
    const closeMobileSidebar = () => {
        if (isMobile.value) {
            mobileSidebarOpen.value = false;
        }
    };
    
    // 添加暗黑模式切换方法
    const toggleDarkMode = () => {
        darkMode.value = !darkMode.value;
        
        // 持久化到 localStorage
        localStorage.setItem('darkMode', darkMode.value);
        
        // 更新 HTML 类名
        updateDarkModeClass();
    };
    
    // 初始化暗黑模式
    const initDarkMode = () => {
        // 从 localStorage 读取或根据系统设置初始化
        const savedDarkMode = localStorage.getItem('darkMode');
        const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        
        darkMode.value = savedDarkMode ? JSON.parse(savedDarkMode) : prefersDark;
        
        // 更新 HTML 类名
        updateDarkModeClass();
    };
    
    // 更新 HTML 类名
    const updateDarkModeClass = () => {
        if (darkMode.value) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    };

    return {
        sidebarCollapsed,
        mobileSidebarOpen,
        darkMode,
        toggleSidebar,
        closeMobileSidebar,
        toggleDarkMode,
        initDarkMode
    };
});